#! python
# -*- coding: utf-8 -*-

CSS_DIR = "css"
JS_DIR = "js"

CSS_RESULT_FILE = "compressed.css.gz"
JS_RESULT_FILE = "compressed.js.gz"

EXCLUDE_FILES = ("donot_compress.js",)
#EXCLUDE_FILES = ("bootstrap.css",)

NEED_NOT_GZIPED_CLONE = True
# Level [0 - 9] recommended is 5
COMPRESSION = 4

import glob, gzip
from os import remove


def make_gzip_compression(process_type="css"):
    # concatenate File
    css_or_js_dir = CSS_DIR if process_type == "css" else JS_DIR

    need_compression_files_list = glob.glob('./' + css_or_js_dir + '/*.' + process_type)

    temp_file_not_zipped = CSS_RESULT_FILE if process_type == "css" else JS_RESULT_FILE
    file_to_write_non_compress = "./" + css_or_js_dir + "/" + temp_file_not_zipped[:-3]
    try:
        need_compression_files_list.remove(file_to_write_non_compress)
    except ValueError:
        pass

    try:
        for exclude_file in ["./" + css_or_js_dir + "/" + file_generator_excl for file_generator_excl in EXCLUDE_FILES]:
                if exclude_file in need_compression_files_list:
                    print "exclude: " + exclude_file
                    need_compression_files_list.remove(exclude_file)
    except NameError:
        #print u"Проверьте EXCLUDE_FILES tuple\n"
        pass

    #print need_compression_files_list
    css_result = open(file_to_write_non_compress, "w")

    for cssFileName in need_compression_files_list:

        css_result.writelines(open(cssFileName, 'r').readlines())
        print "produce: "+ cssFileName

        if len(need_compression_files_list) != need_compression_files_list.index(cssFileName) + 1:
            css_result.write("\n")
# compress File
    gziped_out = gzip.open(file_to_write_non_compress + '.gz', "wb", COMPRESSION)
    gziped_out.writelines(open(file_to_write_non_compress, "r").readlines())

    css_result.close()
    gziped_out.close()

    if not NEED_NOT_GZIPED_CLONE:
        remove(file_to_write_non_compress)


# compress CSS
make_gzip_compression("css")
# compress JS
#make_gzip_compression("js")